import {defineStore} from 'pinia'
import {ref} from 'vue'
import $router from "@/router";
import type SysPermission from "@/type/entity/sys-permission.ts";
import constantRoutes from '@/router/constant-routes.ts'
import toRoutes from "@/router/toRoutes.ts";
import type SysRole from "@/type/entity/sys-role.ts";

/**
 * created by yangtong on 2025/5/18 01:03:49
 * 用户数据的Store
 */
export const useUserStore = defineStore('user', () => {
    const id = ref('')
    const userName = ref('李小萌')
    const realName = ref('李小萌')
    const avatar = ref('https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg')
    const phone = ref('')
    const email = ref('')
    const departCode = ref('')
    const departName = ref('')
    const remark = ref('')
    /**
     * 当前用户的角色
     */
    const roles = ref<SysRole[]>([])
    /**
     * 当前用户的拥有的资源
     */
    const permissions = ref<SysPermission[]>([])

    /**
     * 更新权限的函数，单独抽取出来作为一个方法，是因为当权限更新时，需要同步更新动态路由
     * @param dynamicPermissions
     */
    const updatePermission = (dynamicPermissions: Array<SysPermission>) => {
        let allPermissions: SysPermission[] = []
        allPermissions.push(...constantRoutes)
        allPermissions.push(...dynamicPermissions)
        permissions.value = allPermissions
        let routes = toRoutes(dynamicPermissions);
        //constantRoutes静态路由已经被注册过了，这里仅需注册动态路由
        if (routes) {
            routes.forEach(route => {
                $router.addRoute(route)
            })
        }
    }

    return {id, userName, realName, avatar, phone, email, departCode, departName, remark, roles, permissions, updatePermission}
})